package com.baymax.test.scene.demo.maverick

import android.os.Bundle
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.airbnb.mvrx.MavericksState
import com.airbnb.mvrx.MavericksViewModel
import com.airbnb.mvrx.MavericksViewModelFactory
import com.airbnb.mvrx.ViewModelContext
import com.airbnb.mvrx.withState
import com.baymax.test.scene.BaseScene
import com.baymax.test.scene.addButton
import com.baymax.test.scene.newSceneFlexContainer

class MainCrashDemo : BaseScene() {
    private val vm: VM by sceneViewModel()
    override fun onCreateView(p0: LayoutInflater, p1: ViewGroup, p2: Bundle?): View {
        vm.onEach { st ->
            println("run f $st")
            st.f()
        }
        return p1.newSceneFlexContainer {
            addButton("test pos main loop function") {
                requireView().post {
                    try {
                        Looper.loop()
                    } catch (e: Exception) {
                        println("accur $e")
                    }
                }
            }


            addButton("throw func exception") {
                throw FuncException("test error")
            }
        }
    }

    class FuncException(val s: String) : RuntimeException(s)
    data class Func(val f: () -> Unit) : MavericksState

    class VM(initialState: Func) : MavericksViewModel<Func>(initialState) {
        fun func(r: () -> Unit) {
            setState { copy(f = r) }
        }

        companion object : MavericksViewModelFactory<VM, Func> {

            override fun initialState(viewModelContext: ViewModelContext): Func? {
                return Func {}
            }
        }
    }
}